// import './App.css';
import React, { Component } from 'react';
import { Space, Table, Popconfirm, Button, Input, Divider, Form, Drawer, message,Select } from 'antd';
import axios from 'axios';
import { render } from '@testing-library/react';
import get from "../api/api"
import { nanoid } from "nanoid";

class Bigclass extends Component {
    formRef = React.createRef() //清空输入框内容
    formRef1 = React.createRef()
    formRef2 = React.createRef()
    constructor(props) {
        super(props);
        this.state = {
            visible: false,
            visible1: false,
            visible2: false,
            rowid: null,
            namee: null,
            text: null,
            image: null,
            options:[],
            imageUrl: "",
            columns2:[
                
            ],
            columns: [
                { title: '名字', dataIndex: 'name', key: 'name', },
                
                {
                    title: '图片', dataIndex: '', key: 'image', render: (record) => {

                        return record.image ? <img src={record.image} style={{ width: '100px', height: '100px' }} /> : <p>暂无图片</p>
                    }
                },
               
         
                { title: 'ID', dataIndex: 'class', key: 'classs' },
                {
                    title: '操作',
                    key: 'action',
                    render: (_, record) => (
                        <Space size="middle">
                           
                            <Popconfirm title="确定要删除吗?" onConfirm={this.deleteData.bind(this, record.objectId)} onCancel={this.onClose.bind(this)} okText="确定" cancelText="取消" >
                                <a className="action-link" style={{ color: record.obsoleted ? '#1890ff' : '#fa8c16' }} >删除</a>
                            </Popconfirm>
                        </Space>
                    ),
                },
               

            ],
            data: [], //储存axios获取到的数据
        }
    }
    
    
    
   
    //关闭新增信息对话框
    onClose = () => {
        this.setState({
            imageUrl: "",
            visible: false
        });
        message.error('取消操作');
    };
    //关闭修改信息对话框
    onClose1 = () => {
        this.setState({
            visible1: false
        });
        message.error('取消操作');
    };
    onClose2 = () => {
        this.setState({
            visible2: false
        });
        message.error('取消操作');
    };
    //显示新增信息抽屉
    showDrawer = () => {
        this.setState({
            visible: true
        });
    };
   

    //将数据显示在初始页面
    componentDidMount() {
        this.readData()
        
    }

    //实现读取数据——————get
    readData() {
        get('https://r5ctn9z9.lc-cn-n1-shared.com/1.1/classes/pushds',
            {
                "X-LC-Id": "r5CTN9z96pCW8mI8fx9YxOmw-gzGzoHsz",
                "X-LC-Key": "8gSsl4Sz0ILMiQeMNMA8xQqg",
                'Content-Type': 'application/json'
            }
        )
            .then(res => {
                console.log(res)
                this.setState({
                    data: res.results

                })
                res.results.forEach((r, i) => {

                    r.key = i;
                });
            }).catch(error => {
                console.log(error)
            })
    }

    //新增信息时的Input输入框事件
    handleChange = (e) => {
        console.log(e)
        this.setState({
            [e.target.id]: e.target.value
        })
    }
    //select选择框
    handleChangee = (e) => {
        console.log(e)
        this.setState({
            bcid: e
        })
    }
    //修改信息时的Input输入框事件
    handleChange1 = (e) => {
        this.setState({
            [e.target.id]: e.target.value
        })
    }

    //新增数据——————post
    //新增、修改数据时提交失败时的提示信息
    onFinishFailed = (errorInfo) => {
        console.log(this.state)
        // console.log('Failed:', this.state.imageUrl);
        message.error("按照格式要求输入")
    };
   
    postData = () => {
        
            // console.log(this.state)
            const formData = new FormData();
            formData.append('file', this.state.image);
            formData.append('name', this.state.image.name);
            axios.post('https://api.leancloud.cn/1.1/files/file', formData, {
                headers: {
                    " X-LC-Id": "r5CTN9z96pCW8mI8fx9YxOmw-gzGzoHsz",
                    "X-LC-Key": "8gSsl4Sz0ILMiQeMNMA8xQqg",
                    'Content-Type': 'image/jpeg'
                }
            }).then(response => {
                console.log(response)
                axios.post("https://r5ctn9z9.lc-cn-n1-shared.com/1.1/classes/pushds", {
                    
                    name: this.state.name,
                    image: response.data.url,
                    class: this.state.classs,
                   
                }, {
                    headers: {
                        " X-LC-Id": "r5CTN9z96pCW8mI8fx9YxOmw-gzGzoHsz",
                        "X-LC-Key": "8gSsl4Sz0ILMiQeMNMA8xQqg",
                        'Content-Type': 'application/json'
                    }
                }).then(res => {
                    message.success('添加成功');
                    // console.log('添加成功')
                    this.readData()
                    
                    this.setState({
                        visible: false,
                        image: null,
                        imageUrl: null
                    });
                    this.formRef.current.resetFields() //新增成功后清空输入框中的数据，避免下次点击新增时出现上次输入的数据
                }).catch(error => {
    
                    message.error("按照格式要求输入")
                    console.log(this.state)
    
                });
            })
    
    
    
        
       



    }

    //上传图片
    handleChangeimage = (event) => {
        const file = event.target.files[0];
        const reader = new FileReader();

        reader.onloadend = () => {
            this.setState({
                image: file
            })


            this.setState({
                imageUrl: reader.result
            })
        };

        if (file instanceof Blob) {
            reader.readAsDataURL(file);
        }



    };

   
    // // 实现删除————————delete
    deleteData = (id) => {
        console.log(id)
        axios.delete(`https://r5ctn9z9.lc-cn-n1-shared.com/1.1/classes/pushds/${id}`, {
            headers: {
                " X-LC-Id": "r5CTN9z96pCW8mI8fx9YxOmw-gzGzoHsz",
                "X-LC-Key": "8gSsl4Sz0ILMiQeMNMA8xQqg",
                'Content-Type': 'application/json'

            }
        }) //id前面的 / 不能省略
            .then(res => {
                message.success('删除成功');
                // console.log('删除成功')
                this.readData()
            }).catch(e => {
                message.success("删除失败了，请查看！！！")
            })
    };

    //实现按照姓名查询数据
    queryfn = (e) => {
        console.log(e)
        this.state.text = e.target.value
        console.log(this.state.text)
        window.timer = setTimeout(() => {
            // let data = this.state.data.filter(r => r.xiangqing.includes(this.state.text))
            if (this.state.text !== null) {

                this.readData();
            }

        })

    }
    //点击查询
    text = () => {
        clearTimeout(window.timer)  //防抖查询
        window.timer = setTimeout(() => {
            console.log()
            let data = this.state.data.filter(r => r.xiangqing ? r.xiangqing.includes(this.state.text) : null)
            if (data.length !== 0) {

                this.setState({
                    data
                })
            } else {
                let data = ""
                this.setState({
                    data
                })
            }


        }, 500)
    }


   

    render() {
        let data = this.state.data;
        let columns = this.state.columns;
        let { name, bcid,classs,imageUrl,image } = this.state;
        return (
            <div className="App">
                <Button type="primary" onClick={this.showDrawer.bind(this)} >添加信息 </Button>
                <Input placeholder="请根据姓名查找信息" style={{ marginLeft: '10px', width: '20%' }} onInput={this.queryfn} onKeyPress={this.text} />
                <Button type="primary" onClick={this.text} >查询 </Button>
                <Divider plain>人员信息表格</Divider>
                <Table columns={columns} dataSource={data} pagination={{ pageSize: 10 }} >   </Table>

                <Drawer title="添加个人信息" onClose={this.onClose} visible={this.state.visible}>
                    <Form ref={this.formRef} onFinish={this.postData} onFinishFailed={this.onFinishFailed} autoComplete="off" >
                        <Form.Item
                            name="name"
                            label="名字"
                            rules={[{ required: true, message: '请输入名字', },]} >
                            <Input placeholder="请输入您的姓名" id="name" value={name} onChange={this.handleChange} title='输入2-6位中文汉字' />
                        </Form.Item>
                        <Form.Item
                            name="image"
                            label="图片"
                            rules={[{ required: false, message: '图片', },]}  >
                            <Input placeholder="图片" type='file' id="image" onChange={this.handleChangeimage} title='图片' />

                            <img className='pushimage' src={imageUrl} style={{ maxWidth: '200px' }} alt="商品图片" />
                        </Form.Item>
                        <Form.Item
                            name="classs"
                            label="筛选ID"
                            rules={[{ required: true, message: '筛选ID', },]} >
                            <Input placeholder="筛选ID" id="classs" value={classs} onChange={this.handleChange} title='输入1开头的11位有效手机号' />
                        </Form.Item>
                       
                       

                        <Button onClick={this.onClose.bind(this)}>取消</Button>
                        <Button htmlType="submit" type="primary">完成 </Button>
                    </Form>
                </Drawer>

               

              
            </div>
        );
    }
}
export default Bigclass;

